package com.jbwz.web.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jbwz.web.cms.entity.GoodsLabel;
import com.jbwz.web.cms.entity.vo.GoodsLabelVO;
import com.jbwz.web.cms.mapper.GoodsLabelMapper;
import com.jbwz.web.cms.service.GoodsLabelService;
import com.jbwz.web.common.base.BaseServiceImpl;
import com.jbwz.web.common.base.IBasePage;
import com.jbwz.web.common.util.BeanUtilCommon;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 角色 服务实现类
 *
 * @author yyh
 * @since 2022-05-13 11:12:31
 */
@Service
public class GoodsLabelServiceImpl extends BaseServiceImpl<GoodsLabelMapper, GoodsLabel>
    implements GoodsLabelService {

  @Override
  public IBasePage pageList(IBasePage page, GoodsLabelVO vo) {
    //        return baseMapper.pageList(page, vo);
    return null;
  }

  @Override
  public List<GoodsLabelVO> listByType(GoodsLabelVO vo) {
    QueryWrapper<GoodsLabel> queryWrapper =
        queryWithCid().eq("type", vo.getType()).orderByDesc("hot_count").orderByDesc("create_time");
    return baseMapper.selectList(queryWrapper).stream().map(this::toVO).toList();
  }

  @Override
  public void saveOrUpdateVO(GoodsLabelVO vo) {
    QueryWrapper<GoodsLabel> queryWrapper =
        queryWithCid().eq("type", vo.getType()).eq("name", vo.getName());
    List<GoodsLabel> list = this.list(queryWrapper);
    if (CollectionUtils.isEmpty(list)) {
      save(toEntity(vo));
    }
  }

  @Override
  public void addHotCount(String name) {
    if (StringUtils.hasLength(name)) {
      UpdateWrapper<GoodsLabel> setwrapper =
          updateWithCid().in("name", (Object[]) name.split(",")).setSql("hot_count=hot_count+1");
      this.update(setwrapper);
    }
  }

  @Override
  public GoodsLabelVO toVO(GoodsLabel e) {
    GoodsLabelVO vo = BeanUtilCommon.copy(e, new GoodsLabelVO());
    return vo;
  }

  public GoodsLabel toEntity(GoodsLabelVO vo) {
    GoodsLabel e = BeanUtilCommon.copy(vo, new GoodsLabel());
    e.setCompanyId(getCurrentCid());
    return e;
  }
}
